const NodeCache = require('node-cache');
const logger = require('../utils/logger');

/**
 * 验证码存储服务（使用node-cache作为内存存储）
 * 如果需要Redis，可以参考TY_API的实现
 */
class VerificationCodeService {
  constructor() {
    // 使用node-cache作为存储
    this.codeCache = new NodeCache({ stdTTL: 300 }); // 默认5分钟过期
    this.timeCache = new NodeCache({ stdTTL: 60 });  // 发送时间限制60秒
    logger.info('验证码服务初始化成功（使用内存存储）');
  }

  /**
   * 存储验证码
   * @param {string} phone 手机号
   * @param {string} code 验证码
   * @param {string} type 类型
   * @param {number} expiresIn 过期时间（秒）
   */
  async setVerificationCode(phone, code, type = 'register', expiresIn = 300) {
    try {
      const data = {
        code,
        type,
        timestamp: Date.now(),
        attempts: 0
      };

      this.codeCache.set(phone, data, expiresIn);
      this.timeCache.set(`${phone}_time`, Date.now(), 60);
      
      logger.info(`验证码存储成功: ${phone}, 类型: ${type}, 过期时间: ${expiresIn}秒`);
      return true;
    } catch (error) {
      logger.error(`验证码存储失败: ${phone}, 错误: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取验证码
   * @param {string} phone 手机号
   */
  async getVerificationCode(phone) {
    try {
      const data = this.codeCache.get(phone);
      return data || null;
    } catch (error) {
      logger.error(`验证码获取失败: ${phone}, 错误: ${error.message}`);
      throw error;
    }
  }

  /**
   * 验证验证码
   * @param {string} phone 手机号
   * @param {string} code 验证码
   */
  async verifyCode(phone, code) {
    try {
      const verificationData = this.codeCache.get(phone);
      
      if (!verificationData) {
        return {
          success: false,
          message: '验证码不存在或已过期'
        };
      }
      
      // 检查验证码是否过期
      const now = Date.now();
      const expiresIn = parseInt(process.env.VERIFICATION_CODE_EXPIRES_IN) || 300;
      if (now - verificationData.timestamp > expiresIn * 1000) {
        this.codeCache.del(phone);
        this.timeCache.del(`${phone}_time`);
        return {
          success: false,
          message: '验证码已过期'
        };
      }

      // 检查尝试次数
      const maxAttempts = parseInt(process.env.VERIFICATION_CODE_MAX_ATTEMPTS) || 5;
      if (verificationData.attempts >= maxAttempts) {
        this.codeCache.del(phone);
        this.timeCache.del(`${phone}_time`);
        return {
          success: false,
          message: '验证码尝试次数过多，请重新获取'
        };
      }

      // 验证验证码
      if (verificationData.code !== code) {
        verificationData.attempts++;
        this.codeCache.set(phone, verificationData, 300);
        return {
          success: false,
          message: '验证码错误'
        };
      }

      // 验证成功，删除验证码
      this.codeCache.del(phone);
      this.timeCache.del(`${phone}_time`);
      
      logger.info(`验证码验证成功: ${phone}`);
      return {
        success: true,
        message: '验证码验证成功',
        data: {
          phone,
          type: verificationData.type
        }
      };
    } catch (error) {
      logger.error(`验证码验证失败: ${phone}, 错误: ${error.message}`);
      throw error;
    }
  }

  /**
   * 检查发送频率限制
   * @param {string} phone 手机号
   */
  async checkSendLimit(phone) {
    try {
      const lastSendTime = this.timeCache.get(`${phone}_time`);
      
      if (lastSendTime) {
        const now = Date.now();
        const timeDiff = now - parseInt(lastSendTime);
        
        const sendLimitWindow = parseInt(process.env.SMS_SEND_LIMIT_WINDOW) || 60;
        if (timeDiff < sendLimitWindow * 1000) {
          return {
            allowed: false,
            message: `发送过于频繁，请${sendLimitWindow}秒后再试`,
            remainingTime: Math.ceil((sendLimitWindow * 1000 - timeDiff) / 1000)
          };
        }
      }

      return {
        allowed: true,
        message: '可以发送'
      };
    } catch (error) {
      logger.error(`检查发送限制失败: ${phone}, 错误: ${error.message}`);
      throw error;
    }
  }

  /**
   * 删除验证码
   * @param {string} phone 手机号
   */
  async deleteVerificationCode(phone) {
    try {
      this.codeCache.del(phone);
      this.timeCache.del(`${phone}_time`);
      
      logger.info(`验证码删除成功: ${phone}`);
      return true;
    } catch (error) {
      logger.error(`验证码删除失败: ${phone}, 错误: ${error.message}`);
      throw error;
    }
  }
}

// 创建全局实例
const verificationCodeService = new VerificationCodeService();

module.exports = verificationCodeService;

